<template>
	<div class="outbound">
		<div style="display: flex;justify-content: space-between;">
			<div>
				<el-button type="primary" @click="applyLend">
					申请借出
				</el-button>
			</div>
			<div style="display: flex">
				<el-select v-model="userId" filterable remote placeholder="按申请人查询" :remote-method="getUserList"
					:loading="userLoading" v-if="userRole" @focus="getUserList('')" @change="getTableData"
					style="width: 150px;">
					<el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
					</el-option>
				</el-select>
				<el-select v-model="type" style="width: 120px;margin-left: 10px;" placeholder="按类型查询"
					@change="getTableData">
					<el-option label="卖出商品" :value="0"></el-option>
					<el-option label="员工借出" :value="1"></el-option>
					<el-option label="生产用品" :value="2"></el-option>
					<el-option label="工具耗材" :value="3"></el-option>
					<el-option label="劳保用品" :value="4"></el-option>
				</el-select>
				<el-select v-model="status" style="width: 120px;margin-left: 10px;" placeholder="按状态查询"
					@change="getTableData">
					<el-option label="待出库" :value="0"></el-option>
					<el-option label="待审核中" :value="1"></el-option>
					<el-option label="出库失败" :value="2"></el-option>
					<el-option label="出库申请" :value="3"></el-option>
					<el-option label="出库成功" :value="4"></el-option>
				</el-select>
				<el-button style="margin-left: 10px;" @click="reset" v-debounce>重置</el-button>
			</div>
		</div>
		<div class="goods-table">
			<el-table :data="tableData" v-loading="loading" border stripe style="width: 100%" height="100%">
				<el-table-column prop="i" label="序号" fixed="left" width="50">
				</el-table-column>
				<el-table-column prop="applicant" label="申请人" width="80">
				</el-table-column>
				<el-table-column label="产品列表" width="80">
					<template slot-scope="scope">
						<el-button type="text" @click="partsOpen(scope.row)">
							点击查看
						</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="price" label="出库价格" width="80" v-if="userInfo.roleId === '1'">
				</el-table-column>
				<el-table-column prop="type" label="申请类型" width="100">
					<template slot-scope="scope">
						<el-tag size="medium" color="#304156" style="color: white">
							{{ applicationType(scope.row.type) }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="申请时间" width="100">
				</el-table-column>
				<el-table-column prop="managementName" label="审核人" width="80">
				</el-table-column>
				<el-table-column prop="outboundTime" label="审核时间" width="100">
				</el-table-column>
				<el-table-column prop="status" label="出库状态" width="100">
					<template slot-scope="scope">
						<el-tag v-if="scope.row.status === 0" type="info" size="medium">
							审核通过
						</el-tag>
						<el-tag v-if="scope.row.status === 1" type="warning" size="medium">
							待审核中
						</el-tag>
						<el-tag v-if="scope.row.status === 2" type="danger" size="medium">
							审核失败
						</el-tag>
						<el-tag v-if="scope.row.status === 3" size="medium">
							出库申请
						</el-tag>
						<el-tag v-if="scope.row.status === 4" type="success" size="medium">
							出库成功
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注" fit>
				</el-table-column>
				<el-table-column prop="userId" label="操作" width="240" fixed="right">
					<template slot-scope="scope">
						<el-button size="mini" :type="buttonType(scope.row.status)" @click="examineDialog(scope.row)"
							:disabled="buttonDisabled(scope.row)">
							{{ buttonText(scope.row.status) }}
						</el-button>
						<el-button size="mini" @click="details(scope.row)">详情</el-button>
						<!-- 新增的删除按钮 -->
						<el-button size="mini" type="danger" @click="neng(scope.row)">
									删除
					 </el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-pagination background :current-page="currentPage" :page-size="pageSize" :total="total"
				:page-sizes="[20, 50, 100]" @size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper">
			</el-pagination>
		</div>

		<!-- 查看产品列表弹窗 -->
		<el-dialog style="margin-top:0" :visible.sync="partsShow" width="75%" :title="selectTitle" @close="partsClose">
			<div class="data-table">
				<el-table :data="selectOutbound.outboundPartList" border stripe style="width: 100%" :max-height="500">
					<el-table-column prop="i" fixed="left" label="序号" width="50">
					</el-table-column>
					<el-table-column label="图片" width="115">
						<template slot-scope="scope">
							<el-image :src="READ_IMG_URL + scope.row.image" style="width: 90px; height: 90px;"
								:preview-src-list="new Array(READ_IMG_URL + scope.row.image)">
							</el-image>
						</template>
					</el-table-column>
					<el-table-column prop="isProduct" label="产品类型" width="80">
						<template slot-scope="scope">
							<el-tag v-if="scope.row.isProduct == 0">成品</el-tag>
							<el-tag type="warning" v-if="scope.row.isProduct == 1">零件</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="partName" label="产品名称" fit>
					</el-table-column>
					<el-table-column prop="model" label="产品型号" fit>
					</el-table-column>
					<el-table-column prop="devicesDescribe" label="产品描述" fit>
					</el-table-column>
					<el-table-column prop="remark" label="备注" fit>
					</el-table-column>
					<el-table-column prop="price" label="销售单价" width="80" v-if="userInfo.roleId == '1'">
					</el-table-column>
					<el-table-column prop="count" label="产品库存" width="80">
					</el-table-column>
					<el-table-column prop="outboundCount" label="出库数量" width="80">
					</el-table-column>
					<el-table-column prop="totalPrice" label="总计" width="80" v-if="userInfo.roleId == '1'">
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>

		<!-- 出库审核 -->
		<el-dialog title="出库审核" :visible.sync="examineDialogVisible" width="75%" @close="closeExamineDialog">
			<el-form :model="selectOutbound" inline label-position="top">
				<el-form-item label="申请人">
					<el-input :value="selectOutbound.applicant" readonly>
					</el-input>
				</el-form-item>
				<el-form-item label="出库价格">
					<el-input :value="selectOutbound.price" readonly>
					</el-input>
				</el-form-item>
				<el-form-item label="申请类型">
					<el-select v-model="selectOutbound.type" disabled style="width: 100%;">
						<el-option label="卖出商品" :value="0"></el-option>
						<el-option label="员工借出" :value="1"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="申请时间">
					<el-input :value="selectOutbound.createTime" readonly>
					</el-input>
				</el-form-item>
				<el-form-item label="备注">
					<el-input :value="selectOutbound.remark" readonly>
					</el-input>
				</el-form-item>
				<el-form-item label="产品列表" style="width: 100%;">
					<div class="data-table">
						<el-table :data="selectOutbound.outboundPartList" border stripe style="width: 100%"
							:max-height="500">
							<el-table-column prop="i" fixed="left" label="序号" width="50">
							</el-table-column>
							<el-table-column label="图片" width="115">
								<template slot-scope="scope">
									<el-image :src="READ_IMG_URL + scope.row.image" style="width: 90px; height: 90px;"
										:preview-src-list="new Array(READ_IMG_URL + scope.row.image)">
									</el-image>
								</template>
							</el-table-column>
							<el-table-column prop="isProduct" label="产品类型" width="80">
								<template slot-scope="scope">
									<el-tag v-if="scope.row.isProduct == 0">成品</el-tag>
									<el-tag type="warning" v-if="scope.row.isProduct == 1">零件</el-tag>
								</template>
							</el-table-column>
							<el-table-column prop="partName" label="产品名称" fit>
							</el-table-column>
							<el-table-column prop="model" label="产品型号" fit>
							</el-table-column>
							<el-table-column prop="devicesDescribe" label="产品描述" fit>
							</el-table-column>
							<el-table-column prop="remark" label="备注" fit>
							</el-table-column>
							<el-table-column prop="price" label="销售单价" width="80" v-if="userInfo.roleId === '1'">
							</el-table-column>
							<el-table-column prop="outboundCount" label="出库数量" width="80">
							</el-table-column>
							<el-table-column prop="totalPrice" label="总计" width="80">
							</el-table-column>
						</el-table>
					</div>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="danger" @click="examine(2)" v-debounce>
					不通过
				</el-button>
				<el-button type="success" @click="examine(0)" v-debounce>
					通过
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import warehouseApi from '../../../api/warehouse';
import userApi from '../../../api/user';
import config from '../../../api/apiURL.js';
export default {
	data() {
		return {
			READ_IMG_URL: config.READ_IMG_URL,
			userInfo: {},
			userRole: false,
			tableData: [],
			selectOutbound: {},
			loading: false,
			currentPage: 1,
			pageSize: 50,
			total: 0,
			userId: null,
			type: null,
			status: null,
			userLoading: false,
			userList: [],
			examineDialogVisible: false,
			selectTitle: "",
			partsShow: false,
		}
	},
	created() {
		this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
		if (this.userInfo.roleId === "1" || this.userInfo.roleId === "5") {
			this.userRole = true;
		}
		this.getTableData();
	},
	methods: {
		// 获取列表数据
		getTableData() {
			this.loading = true;
			const data = {
				userId: this.userId,
				type: this.type,
				status: this.status,
				currentPage: this.currentPage,
				pageSize: this.pageSize
			}
			this.tableData = new Array;
			warehouseApi.getDevicesOutboundList(data).then(res => {
				if (res.code === 200) {
					this.total = res.data.total;
					this.tableData = res.data.outboundVoList.map((item, index) => {
						item.i = (this.currentPage - 1) * this.pageSize + index + 1
						return item;
					})
				}
			}).finally(() => {
				this.loading = false;
			})
		},
		// 删除出库记录
        neng(row) {
            this.$confirm('是否要删除此出库记录？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const loading = this.$loading({
                    lock: true,
                    text: '删除中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                warehouseApi.deleteOutbound(row).then(res => {
                    if (res.code === 200) {
                        this.$message.success("删除成功");
                        // 从 tableData 中移除已删除的记录
                        this.tableData = this.tableData.filter(item => item.id !== row.id);
                    } else {
                        this.$message.error("删除失败");
                    }
                }).finally(() => {
                    loading.close();
                });
            }).catch(() => {
                // 用户点击了取消按钮时执行的操作
            });
        },
		// 页码变化
		handleCurrentChange(currentPage) {
			this.currentPage = currentPage;
			this.getTableData();
		},
		// 页码条数变化
		handleSizeChange(pageSize) {
			this.pageSize = pageSize;
			this.getTableData();
		},
		// 展示零件列表
		partsOpen(row) {
			row.outboundPartList.forEach((part, index) => {
				part.i = index + 1
			})
			this.selectOutbound = row;
			this.selectTitle = row.applicant;
			this.partsShow = true;
		},
		// 关闭零件列表
		partsClose() {
			this.selectOutbound = {}
			this.selectTitle = ""
		},
		// 出库审核弹窗
		examineDialog(row) {
			if (row.status === 0 &&
				(this.userInfo.roleId === "1" ||
					this.userInfo.roleId === "4")) {
				// 库管、管理员
				// 申请成功，一键出库
				this.$confirm("是否要一键出库？", "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					const data = {
						id: row.id,
						status: 4
					}
					warehouseApi.examineDevicesOutbound(data).then(res => {
						if (res.code === 200) {
							this.$message.success("操作成功");
							this.getTableData();
						}
					})
				})
			} else if (row.status === 1) {
				// 出库审核
				this.selectOutbound = row;
				this.selectOutbound.outboundPartList = row.outboundPartList.map((item, index) => {
					item.i = index + 1;
					return item;
				})
				this.examineDialogVisible = true;
			} else if (row.status === 3) {
				this.$confirm("是否要申请出库？", "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					const data = {
						id: row.id,
						status: 1
					}
					warehouseApi.examineDevicesOutbound(data).then(res => {
						if (res.code === 200) {
							this.$message.success("操作成功");
							this.getTableData();
						}
					})
				})
			}
		},
		//申请类型
		applicationType(type) {
			switch (type) {
				case 0:
					return "卖出商品"
				case 1:
					return "员工借出"
				case 2:
					return "生产用品"
				case 3:
					return "工具耗材"
				case 4:
					return "劳保用品"
				default:
					return ""
			}
		},
		// 获取用户列表
		getUserList(query) {
			this.userLoading = true;
			const data = {
				nickName: query,
			}
			userApi.fuzzyQuery(data).then(res => {
				if (res.code === 200) {
					this.userList = res.data.userVoList
				}
			}).finally(() => {
				this.userLoading = false;
			})
		},
		// 申请借出
		applyLend() {
			this.$router.push({
				path: "/warehouse/outbound/addOutbound"
			})
		},
		// 审核按钮类型
		buttonType(status) {
			if (status === 0) {
				return ""
			} else if (status === 2) {
				return "danger"
			} else if (status === 3) {
				return "primary"
			} else if (status === 4) {
				return "success"
			}
			return "warning"
		},
		// 审核按钮是否禁用
		buttonDisabled(row) {
			if (row.status === 4 || row.status === 2) {
				return true;
			} else if (row.status === 1 && !this.userRole) {
				// 状态为待审核，权限不为管理员或厂长
				return true;
			} else if (row.status === 3 && !(row.userId === this.userInfo.id) &&
				!this.userRole) {
				// 状态为出库申请，且不为本人，不为管理员或厂长
				return true;
			} else if (row.status === 0 && !(this.userInfo.roleId === "4") &&
				!(this.userInfo.roleId === "1")) {
				// 状态为一键出库，不为库管，管理员
				return true;
			} else {
				return false;
			}
		},
		// 审核按钮文字
		buttonText(status) {
			if (status === 0) {
				return "一键出库"
			} else if (status === 2) {
				return "审核失败"
			} else if (status === 3) {
				return "申请出库"
			} else if (status === 4) {
				return "出库成功"
			}
			return "待审核中"
		},
		// 审核弹窗关闭
		closeExamineDialog() {
			this.selectOutbound = {};
		},
		// 审核
		examine(index) {
			let msg = "";
			if (index === 0) {
				msg = "确定要通过该出库申请？"
			} else if (index === 2) {
				msg = "确定要驳回该出库申请？"
			}
			this.$confirm(msg, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				const data = {
					id: this.selectOutbound.id,
					status: index,
				}
				warehouseApi.examineDevicesOutbound(data).then(res => {
					if (res.code === 200) {
						this.$message.success("操作成功");
						this.examineDialogVisible = false;
						this.closeExamineDialog();
						this.getTableData();
					}
				})
			})
		},
		reset() {
			this.userId = null;
			this.type = null;
			this.status = null;
			this.currentPage = 1;
			this.getTableData();
		},
		details(row) {
			localStorage.setItem("outboundId", row.id)
			this.$router.push({
				path: "/warehouse/outbound/addOutbound"
			})
		}
	}
}
</script>

<style scoped>
.outbound {
	height: 100%;
}

.goods-table {
	height: 94%;
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	justify-content: center;
	margin-top: 10px;
}

.imgUrl {
	width: 100px;
	height: 100px;
	object-fit: cover;
	/* 保持原始宽高比，填充容器 */
}

.htimg {
	width: 150px;
	height: 150px;
	object-fit: cover;
	/* 保持原始宽高比，填充容器 */
}

.el-form-item {
	width: 400px;
	margin-right: 20px;
}
</style>